<template>
  <div class="mine">
    <van-nav-bar
      style="height: 46px; font-size: 12px"
      title="订单确认"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <div class="celladdress">
      <van-cell title="服务地址" icon="location-o" size="large" @click="showPopup" center>
        <template #label>
          <van-row gutter="40">
            <van-col span="8">姓名：{{ content[0] }}</van-col>
            <van-col span="12">电话：{{ content[1] }}</van-col>
            <van-col span="16">地址：{{ content[2] }}</van-col>
          </van-row>
        </template>
      </van-cell>
    </div>
    <van-popup v-model="show" position="bottom" :style="{ height: '80%' }">
      <van-address-list
        v-model="chosenAddressId"
        :list="addressData"
        :disabled-list="disabledList"
        disabled-text="以下地址超出配送范围"
        add-button-text="确定"
        @add="confirmaddress(chosenAddressId)"
      />
    </van-popup>
    <div class="cellaorder">
      <van-cell title="订单详情" icon="balance-list-o" size="large">
        <template #label>
          <van-row gutter="30" v-for="orderLine in orderGoods" :key="orderLine.goods_id">
            <van-col span="10">{{ orderLine.goods_name }}</van-col>
            <van-col span="6">￥{{ orderLine.goods_price }}</van-col>
            <van-col span="6">+{{ orderLine.goods_number }}</van-col>
          </van-row>
          <van-divider
            :style="{
              color: '#cdcdcd',
              borderColor: '#cdcdcd',
              padding: '0 2px',
              background: '#cdcdcd',
            }"
          ></van-divider>
          <van-row>
            <van-col span="10" offset="12">总价：￥{{ total }}</van-col>
          </van-row>
        </template>
      </van-cell>
    </div>
    <div class="celltime">
      <van-cell
        title="服务时间"
        icon="clock-o"
        :value="daytime | dateFormat"
        size="large"
        @click="showPopup2"
      />
    </div>
    <van-popup v-model="show2" position="bottom" :style="{ height: '50%' }">
      <van-datetime-picker
        v-model="currentDate"
        type="datetime"
        title="选择完整时间"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="confirmtime()"
        @cancel="canceltime()"
      />
    </van-popup>

    <van-button
      color="linear-gradient(to right, #ff6034, #ee0a24)"
      :block="true"
      style="
        width: 278px;
        height: 40px;
        border-radius: 22px;
        margin: 30px auto;
        font-size: 15px;
      "
      @click="submit()"
    >确认提交</van-button>
  </div>
</template>

<script>
import { get, post, post_json } from "@/http/axios";
// 引入vuex的辅助函数
import { mapActions, mapState, mapMutations, mapGetters } from "vuex";
import { Toast } from 'vant';
export default {
  data() {
    return {
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2031, 10, 1),
      currentDate: new Date(),
      daytime: "",
      content: [],
      show: false,
      show2: false,
      chosenAddressId: "",
      disabledList: [
        {
          id: '3',
          name: '王五',
          tel: '1320000000',
          address: '浙江省杭州市滨江区江南大道 15 号',
        },
      ],
      total: this.$route.query.total
    };
  },
  computed: {
    ...mapState("order", ["orderGoods"]),
    ...mapState("address", ["addressData"]),
    findDefaultId(){
      this.addressData.forEach(element => {
        if (element.isDefault === true) {
          this.chosenAddressId = element.id
        }
      });
    },
    addressList() {
      // 筛选地址数据 生成匹配组件的数据
      let addressArr = this.addressData;
      let addressList = [];
      if (!addressArr) {
        return;
      }
      addressArr.forEach((item, index) => {
        let addressObj = {};
        (addressObj.id = item.id),
          (addressObj.name = item.name),
          (addressObj.tel = item.tel),
          (addressObj.address =
            item.province + item.city + item.area + item.address),
          (addressObj.isDefault = item.isDefault);
        addressList.push(addressObj);
      });
      return addressList;
    },
  },
  methods: {
    ...mapActions('order',['resetShopCart']),
    onClickLeft() {
      this.$router.go(-1);
    },
    showPopup() {
      this.show = true;
    },
    showPopup2() {
      this.show2 = true;
    },
    confirmtime() {
      this.show2 = false;
      this.daytime = String(this.currentDate);
    },
    canceltime() {
      this.show2 = false;
    },
    confirmaddress(chosenAddressId) {
      let addressData = {};
      for (let index = 0; index < this.addressData.length; index++) {
        addressData = this.addressData[index];
        if (chosenAddressId == addressData.id) {
          this.content[0] = addressData.name;
          this.content[1] = addressData.tel;
          this.content[2] = addressData.address;
        }
      }
      this.show = false;
    },
    async submit() {
      let dayTime = this.getTimestamp(this.daytime)/1000;
      let goods = []
      console.log(this.orderGoods);
      let goods_sum = 0
      this.orderGoods.forEach(element => {
        if (element.goods_big_logo === '') {
          element.goods_pics = 'http://127.0.0.1:8888/tmp_uploads\\0de02538840f46310d344a883a5ec930.png'
        }else{
          element.goods_pics = element.goods_big_logo
        }
        goods_sum+= element.goods_number
        goods.push(element)
      });
      if (this.chosenAddressId) {
          let data = {
            user_id: JSON.parse(localStorage.getItem('userInfo')).id,
            order_price: Number(this.total),
            order_fapiao_title: '个人',
            order_fapiao_company: this.content[0],
            order_fapiao_content: this.content[1],
            consignee_addr: this.content[2],
            pay_status: '0',
            create_time: dayTime,
            update_time: dayTime,
            goods: goods,
            goods_sum: goods_sum
          };
          console.log(data);
          await this.axios.post('orders', data).then(res => {
            console.log(res.data);
            if (res.data.meta.status === 201) {
              Toast.success('提交成功');
              this.resetShopCart()
              setTimeout(this.$router.push({path: "Order"}),500)
            }
          })
        
      } else {
        Toast.fail('提交失败');
      }
    },
    getTimestamp(time) {
      //把时间日期转成时间戳 方法
      return new Date(time).getTime();
    },
  },
  created() {
    console.log(this.orderGoods);
    // this.findDefaultId()
    this.daytime = String(new Date());
  },
  mounted() {
    
  },
};
</script>

<style scoped>
.celladdress,
.cellaorder,
.celltime {
  margin: 10px auto;
  box-shadow: 2px 2px 2px 2px rgba(158, 117, 255, 0.2);
  transition: 0.3s;
  width: 95%;
  border-radius: 5px;
}
/deep/ .van-icon-edit{
  display: none;
}
/deep/ .van-col--16{
  margin-top: 20px;
}
/deep/ .van-icon-location-o{
  position: absolute;
  top: 12px;
  left: 16px;
}
/deep/ .van-cell--center{
  padding-left: 35px;
}
</style>